<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElDialog, ElButton } from 'element-plus'
import { CloseBold } from '@element-plus/icons-vue'
import axios from 'axios'
import showMsg from '@/utils/showMsg'
const showLoginBox = defineModel('showLoginBox', { type: Boolean })
const router = useRouter()
const username = ref('')
const password = ref('')

const login = async () => {
  if (!username.value || !password.value)
    return showMsg({
      type: 'error',
      msg: '请输入账号和密码'
    })
  try {
    const response = await axios.post(`/api/login`, {
      username: username.value,
      password: password.value
    })
    const { data } = response
    console.log(data)
    if (data.code === 500)
      return showMsg({
        type: 'error',
        msg: '账号或密码错误'
      })
    else if (data.code === 200) {
      localStorage.setItem('token', data.token)
      localStorage.setItem('username', username.value)
      showMsg({
        type: 'success',
        msg: '登录成功',
        duration: 1000,
        onClose: () => {
          username.value = ''
          password.value = ''
          router.push({ name: 'home' })
        }
      })
    }
  } catch (err) {
    console.log(err)
    showMsg({
      type: 'error',
      msg: '登录失败，请稍后重试'
    })
  }
}
</script>
<template>
  <el-dialog
    class="login-box"
    v-model="showLoginBox"
    width="500"
    style="border-radius: 20px; background-color: #f1ce9a; box-shadow: 0 0 0 20px #9a5e37"
    :show-close="false"
  >
    <template #header="{ close }">
      <div style="display: flex">
        <close-bold
          style="width: 32px; height: 32px; margin-left: auto; color: #9a5e37"
          @click="close"
        />
      </div>
    </template>
    <div style="display: flex; align-items: center">
      <span class="base-border" style="padding: 0 4px; white-space: nowrap">账号</span>
      <input
        v-model="username"
        class="base-border"
        style="margin-left: 24px; line-height: 44px; overflow: hidden"
      />
    </div>
    <div style="display: flex; align-items: center; margin-top: 24px">
      <span class="base-border" style="padding: 0 4px; white-space: nowrap">密码</span>
      <input
        v-model="password"
        class="base-border"
        style="margin-left: 24px; line-height: 44px; overflow: hidden"
      />
    </div>
    <el-button
      size="large"
      color="#9a5e37"
      :round="true"
      style="width: 100%; margin-top: 24px; font-size: 28px"
      @click="login"
      >确认</el-button
    >
  </el-dialog>
</template>
<style scoped>
.base-border {
  background-color: #ffe2b3;
  border: 6px solid #f55a36;
  font-size: 28px;
  border-radius: 20px;
}
</style>
